<template>
	<view class="container">
		<view class="content">
			<!-- 零钱理财 -->
			<view class="collapse-container">
				<view class="collapse-header" @click="toggleCollapse('change')">
					<text class="collapse-title">零钱理财</text>
					<text class="collapse-value">{{ totalChangeProfit }} 元</text>
					<text class="collapse-arrow" :class="{ 'arrow-down': !collapsedStates.change }">▼</text>
				</view>
				<transition name="slide-fade">
					<view v-show="!collapsedStates.change" class="collapse-content">
						<view v-if="changeMoneyList.length > 0" class="product-list">
							<view v-for="(item, index) in changeMoneyList.filter(i => i.status === 1)" :key="index"
								class="product-card">
								<view class="card-header">
									<view class="header-left">
										<text class="product-name">{{ item.changeMoney.name }}</text>
									</view>
									<text class="product-status" :class="{ 'status-active': item.status === 1 }">
										{{ getStatusText(item.status) }}</text>
								</view>
								<view class="card-content">
									<view class="info-row">
										<view class="info-item">
											<text class="label">起投金额</text>
											<text class="value">{{ item.changeMoney.invesmoney }}元</text>
										</view>
										<view class="info-item">
											<text class="label">起投时间</text>
											<text class="value">{{ formatDate(item.starttime) }}</text>
										</view>
									</view>
									<view class="info-row">
										<view class="info-item">
											<text class="label">投资期限</text>
											<text class="value">{{ item.changeMoney.investerm }}</text>
										</view>
										<view class="info-item">
											<text class="label">平均收益率</text>
											<text class="value highlight">{{ item.averyield }}%</text>
										</view>
									</view>
									<view class="profit-row">
										<view class="profit-info">
											<text class="label">预期收益</text>
											<text class="value">{{ item.profit }}元</text>
											<text v-if="item.actualProfit" class="actual-profit">(实际:{{
												item.actualProfit }}元)</text>
										</view>
										<view class="action-btn" :class="{ 'disabled': item.status !== 1 }">
											<u-button type="error" @click="handleRevoke('change', item)"
												:disabled="item.status !== 1">撤销</u-button>
										</view>
									</view>
								</view>
							</view>
						</view>
						<view v-else class="empty-tip">
							<text>很抱歉！暂时还没有查询到您的零钱理财信息</text>
						</view>
					</view>
				</transition>
			</view>

			<!-- 工资理财 -->
			<view class="collapse-container">
				<view class="collapse-header" @click="toggleCollapse('pay')">
					<text class="collapse-title">工资理财</text>
					<text class="collapse-value">{{ totalPayProfit }} 元</text>
					<text class="collapse-arrow" :class="{ 'arrow-down': !collapsedStates.pay }">▼</text>
				</view>
				<transition name="slide-fade">
					<view v-show="!collapsedStates.pay" class="collapse-content">
						<view v-if="payMoneyList.length > 0" class="product-list">
							<view v-for="(item, index) in payMoneyList.filter(i => i.status === 1)" :key="index"
								class="product-card">
								<view class="card-header">
									<view class="header-left">
										<text class="product-name">{{ item.type === 1 ? '国债' : '期货' }}</text>
									</view>
									<text class="product-status" :class="{ 'status-active': item.status === 1 }">{{
										getStatusText(item.status) }}</text>
								</view>
								<view class="card-content">
									<view class="info-row">
										<view class="info-item">
											<text class="label">月投金额</text>
											<text class="value">{{ item.payMoney.monthmoney }}元</text>
										</view>
										<view class="info-item">
											<text class="label">起投时间</text>
											<text class="value">{{ formatDate(item.starttime) }}</text>
										</view>
									</view>
									<view class="info-row">
										<view class="info-item">
											<text class="label">投资期限</text>
											<text class="value">{{ item.payMoney.investerm }}</text>
										</view>
										<view class="info-item">
											<text class="label">平均收益率</text>
											<text class="value highlight">{{ item.averyield }}%</text>
										</view>
									</view>
									<view class="profit-row">
										<view class="profit-info">
											<text class="label">预期收益</text>
											<text class="value">{{ item.profit }}元</text>
											<text v-if="item.actualProfit" class="actual-profit">(实际:{{
												item.actualProfit }}元)</text>
										</view>
										<view class="action-btn" :class="{ 'disabled': item.status !== 1 }">
											<u-button type="error" @click="handleRevoke('pay', item)"
												:disabled="item.status !== 1">撤销</u-button>
										</view>
									</view>
								</view>
							</view>
						</view>
						<view v-else class="empty-tip">
							<text>很抱歉！暂时还没有查询到您的工资理财信息</text>
						</view>
					</view>
				</transition>
			</view>

			<!-- 期限理财 -->
			<view class="collapse-container">
				<view class="collapse-header" @click="toggleCollapse('term')">
					<text class="collapse-title">期限理财</text>
					<text class="collapse-value">{{ totalTermProfit }} 元</text>
					<text class="collapse-arrow" :class="{ 'arrow-down': !collapsedStates.term }">▼</text>
				</view>
				<transition name="slide-fade">
					<view v-show="!collapsedStates.term" class="collapse-content">
						<view v-if="termFinancialList.length > 0" class="product-list">
							<view v-for="(item, index) in termFinancialList.filter(i => i.status === 1)" :key="index"
								class="product-card">
								<view class="card-header">
									<view class="header-left">
										<text class="product-name">{{ item.termFinancial.name }}</text>
									</view>
									<text class="product-status" :class="{ 'status-active': item.status === 1 }">{{
										getStatusText(item.status) }}</text>
								</view>
								<view class="card-content">
									<view class="info-row">
										<view class="info-item">
											<text class="label">起投金额</text>
											<text class="value">{{ item.termFinancial.leastmoney }}元</text>
										</view>
										<view class="info-item">
											<text class="label">起投时间</text>
											<text class="value">{{ formatDate(item.starttime) }}</text>
										</view>
									</view>
									<view class="info-row">
										<view class="info-item">
											<text class="label">投资期限</text>
											<text class="value">{{ item.termFinancial.investerm }}</text>
										</view>
										<view class="info-item">
											<text class="label">平均收益率</text>
											<text class="value highlight">{{ item.averyield }}%</text>
										</view>
									</view>
									<view class="profit-row">
										<view class="profit-info">
											<text class="label">预期收益</text>
											<text class="value">{{ item.profit }}元</text>
											<text v-if="item.actualProfit" class="actual-profit">(实际:{{
												item.actualProfit }}元)</text>
										</view>
										<view class="action-btn" :class="{ 'disabled': item.status !== 1 }">
											<u-button type="error" @click="handleRevoke('term', item)"
												:disabled="item.status !== 1">撤销</u-button>
										</view>
									</view>
								</view>
							</view>
						</view>
						<view v-else class="empty-tip">
							<text>很抱歉！暂时还没有查询到您的期限理财信息</text>
						</view>
					</view>
				</transition>
			</view>

			<!-- 基金理财 -->
			<view class="collapse-container">
				<view class="collapse-header" @click="toggleCollapse('fund')">
					<text class="collapse-title">基金理财</text>
					<text class="collapse-value">{{ totalFundProfit }} 元</text>
					<text class="collapse-arrow" :class="{ 'arrow-down': !collapsedStates.fund }">▼</text>
				</view>
				<transition name="slide-fade">
					<view v-show="!collapsedStates.fund" class="collapse-content">
						<view v-if="fundProductList.length > 0" class="product-list">
							<view v-for="(item, index) in fundProductList.filter(i => i.status === 1)" :key="index"
								class="product-card">
								<view class="card-header">
									<view class="header-left">
										<text class="product-name">{{ item.fundProduct.funddesc }}</text>
									</view>
									<text class="product-status" :class="{ 'status-active': item.status === 1 }">{{
										getStatusText(item.status) }}</text>
								</view>
								<view class="card-content">
									<view class="info-row">
										<view class="info-item">
											<text class="label">起投金额</text>
											<text class="value">{{ item.fundProduct.leastmoney }}元</text>
										</view>
										<view class="info-item">
											<text class="label">起投时间</text>
											<text class="value">{{ formatDate(item.starttime) }}</text>
										</view>
									</view>
									<view class="info-row">
										<view class="info-item">
											<text class="label">投资期限</text>
											<text class="value">{{ item.fundProduct.investerm }}</text>
										</view>
										<view class="info-item">
											<text class="label">平均收益率</text>
											<text class="value highlight">{{ item.averyield }}%</text>
										</view>
									</view>
									<view class="profit-row">
										<view class="profit-info">
											<text class="label">预期收益</text>
											<text class="value">{{ item.profit }}元</text>
											<text v-if="item.actualProfit" class="actual-profit">(实际:{{
												item.actualProfit }}元)</text>
										</view>
										<view class="action-btn" :class="{ 'disabled': item.status !== 1 }">
											<u-button type="error" @click="handleRevoke('fund', item)"
												:disabled="item.status !== 1">撤销</u-button>
										</view>
									</view>
								</view>
							</view>
						</view>
						<view v-else class="empty-tip">
							<text>很抱歉！暂时还没有查询到您的基金理财信息</text>
						</view>
					</view>
				</transition>
			</view>
		</view>
	</view>
</template>

<script>
export default {
	data() {
		return {
			changeMoneyList: [],
			payMoneyList: [],
			termFinancialList: [],
			fundProductList: [],
			totalChangeProfit: '0.00',
			totalPayProfit: '0.00',
			totalTermProfit: '0.00',
			totalFundProfit: '0.00',
			collapsedStates: {
				change: true,
				pay: true,
				term: true,
				fund: true
			}
		}
	},
	onLoad() {
		this.loadData()
		// 启动定时器更新收益
		this.startProfitTimer()
	},
	onUnload() {
		// 清除定时器
		if (this.profitTimer) {
			clearInterval(this.profitTimer)
		}
	},
	methods: {
		// 加载数据
		async loadData() {
			try {
				const user = uni.getStorageSync("user")
				uni.request({
					url: '/api/my/manage',
					method: 'POST',
					data: {
						user: user
					},
					success: (res) => {
						console.log(res);
						this.changeMoneyList = res.data.userChangeMoneyList
						this.payMoneyList = res.data.userPayMoneyList
						this.termFinancialList = res.data.userTermFinancialList
						this.fundProductList = res.data.userFundProductList
						this.calculateProfits()
					}
				})
			} catch (e) {
				this.$u.toast('加载数据失败')
			}
		},

		// 获取状态文本
		getStatusText(status) {
			const statusMap = {
				1: '持有中',
				2: '已失效',
				3: '已撤销'
			}
			return statusMap[status] || '未知'
		},

		// 处理撤销操作
		async handleRevoke(type, item) {
			try {
				await this.$u.modal.confirm('提示', `确定撤销${item.name || '该产品'}吗？`)

				let url = ''
				let params = {}

				switch (type) {
					case 'change':
						url = '/user/revokeUserChangeMoney'
						params = {
							userChangeMoneyId: item.id
						}
						break
					case 'pay':
						url = '/user/revokeUserPayMoney'
						params = {
							userPayMoneyId: item.id
						}
						break
					case 'term':
						url = '/user/revokeUserTermFinancial'
						params = {
							userTermFinancialId: item.id
						}
						break
					case 'fund':
						url = '/user/revokeUserFundProduct'
						params = {
							userFundProductId: item.id
						}
						break
				}

				await this.$u.api.put(url, params)
				this.$u.toast('撤销成功')
				this.loadData()
			} catch (e) {
				if (e !== 'cancel') {
					this.$u.toast('撤销失败')
				}
			}
		},

		// 计算实际收益
		calculateActualProfit(item) {
			if (!item || item.status !== 1) return item.profit;
			// 获取投资期限文本
			let investTermText = '';
			if (item.changeMoney) {
				investTermText = item.changeMoney.investerm;
			} else if (item.payMoney) {
				investTermText = item.payMoney.investerm;
			} else if (item.termFinancial) {
				investTermText = item.termFinancial.investerm;
			} else if (item.fundProduct) {
				investTermText = item.fundProduct.investerm;
			}
			// 将文字形式的投资期限转换为天数
			let investTermDays;
			if (investTermText === '半年') {
				investTermDays = 183; // 半年约等于183天
			} else if (investTermText === '一个月') {
				investTermDays = 30;
			} else if (investTermText === '一年') {
				investTermDays = 365;
			} else {
				// 如果不匹配任何已知的文字形式，返回30天作为默认值
				investTermDays = 30;
			}

			const now = new Date();
			const startDate = new Date(item.starttime);

			if (startDate > now) return 0;

			const endDate = new Date(startDate.getTime() + investTermDays * 24 * 60 * 60 * 1000);

			if (now >= endDate) return item.profit;

			const investedDays = (now - startDate) / (1000 * 60 * 60 * 24);
			const timeRatio = Math.min(1.0, investedDays / investTermDays);

			return (item.profit * timeRatio).toFixed(2);
		},

		// 解析投资期限
		parseInvestTerm(term) {
			// term = term.trim()

			// if (term.includes('天')) {
			// 	return parseInt(term)
			// } else if (term.includes('个月') || term.includes('月')) {
			// 	return parseInt(term) * 30
			// } else if (term.includes('年')) {
			// 	return parseInt(term.replace('一', '1').replace('二', '2').replace('三', '3')
			// 		.replace('四', '4').replace('五', '5').replace('半', '0.5')) * 365
			// }

			// return 30
		},

		// 计算总收益
		calculateProfits() {
			// 计算各类理财的实际收益
			this.changeMoneyList.forEach(item => {
				item.actualProfit = this.calculateActualProfit(item)
			})
			this.payMoneyList.forEach(item => {
				item.actualProfit = this.calculateActualProfit(item)
			})
			this.termFinancialList.forEach(item => {
				item.actualProfit = this.calculateActualProfit(item)
			})
			this.fundProductList.forEach(item => {
				item.actualProfit = this.calculateActualProfit(item)
			})

			// 计算总收益
			this.totalChangeProfit = this.changeMoneyList.reduce((sum, item) => sum + parseFloat(item.actualProfit ||
				item.profit), 0).toFixed(2)
			this.totalPayProfit = this.payMoneyList.reduce((sum, item) => sum + parseFloat(item.actualProfit || item
				.profit), 0).toFixed(2)
			this.totalTermProfit = this.termFinancialList.reduce((sum, item) => sum + parseFloat(item.actualProfit ||
				item.profit), 0).toFixed(2)
			this.totalFundProfit = this.fundProductList.reduce((sum, item) => sum + parseFloat(item.actualProfit ||
				item.profit), 0).toFixed(2)
		},

		// 启动定时器更新收益
		startProfitTimer() {
			this.profitTimer = setInterval(() => {
				this.calculateProfits()
			}, 1000)
		},

		// 切换折叠状态
		toggleCollapse(type) {
			this.collapsedStates[type] = !this.collapsedStates[type]
		},
		// 返回格式化时间yyyy-MM-dd
		formatDate(date) {
			if (!date) return '';
			const d = new Date(date);
			const year = d.getFullYear();
			const month = String(d.getMonth() + 1).padStart(2, '0');
			const day = String(d.getDate()).padStart(2, '0');
			return `${year}-${month}-${day}`;
		}
	}
}
</script>

<style lang="scss" scoped>
.container {
	min-height: 100vh;
	background-color: #f5f5f5;

	.content {
		padding: 20rpx;
	}

	.product-list {
		padding: 20rpx 0;

		.product-card {
			background: #fff;
			border-radius: 12rpx;
			margin-bottom: 20rpx;
			padding: 30rpx;
			box-shadow: 0 2rpx 12rpx rgba(0, 0, 0, 0.05);

			.card-header {
				display: flex;
				justify-content: space-between;
				align-items: center;
				margin-bottom: 20rpx;

				.header-left {
					display: flex;
					align-items: center;

					.product-index {
						width: 40rpx;
						height: 40rpx;
						line-height: 40rpx;
						text-align: center;
						background: #f5f5f5;
						border-radius: 20rpx;
						font-size: 24rpx;
						color: #666;
						margin-right: 16rpx;
					}

					.product-name {
						font-size: 32rpx;
						font-weight: bold;
						color: #333;
					}
				}

				.product-status {
					font-size: 24rpx;
					color: #999;
					padding: 4rpx 12rpx;
					border-radius: 20rpx;
					background: #f5f5f5;

					&.status-active {
						color: #4CAF50;
						background: rgba(76, 175, 80, 0.1);
					}
				}
			}

			.card-content {
				.info-row {
					display: flex;
					justify-content: space-between;
					margin-bottom: 20rpx;

					.info-item {
						flex: 1;

						.label {
							font-size: 24rpx;
							color: #999;
							margin-bottom: 8rpx;
							display: block;
						}

						.value {
							font-size: 28rpx;
							color: #333;

							&.highlight {
								color: #4CAF50;
								font-weight: bold;
							}
						}
					}
				}

				.profit-row {
					display: flex;
					justify-content: space-between;
					align-items: center;
					margin-top: 20rpx;
					padding-top: 20rpx;
					border-top: 1px solid #eee;

					.profit-info {
						.label {
							font-size: 24rpx;
							color: #999;
							margin-bottom: 8rpx;
							display: block;
						}

						.value {
							font-size: 32rpx;
							color: #333;
							font-weight: bold;
						}

						.actual-profit {
							font-size: 24rpx;
							color: #4CAF50;
							margin-left: 10rpx;
						}
					}

					.action-btn {
						:deep(.u-button) {
							background: #ff4d4f;
							border: none;
							color: #fff;
							font-size: 24rpx;
							padding: 0 20rpx;
							height: 48rpx;
							line-height: 48rpx;
							border-radius: 24rpx;
							box-shadow: 0 2rpx 8rpx rgba(255, 77, 79, 0.2);
							transition: all 0.3s ease;

							&:active {
								transform: scale(0.95);
								box-shadow: 0 1rpx 4rpx rgba(255, 77, 79, 0.1);
							}
						}

						&.disabled {
							:deep(.u-button) {
								background: #f5f5f5;
								color: #999;
								box-shadow: none;
							}
						}
					}
				}
			}
		}
	}

	.empty-tip {
		padding: 30rpx;
		text-align: center;
		color: #999;
		background: #fff;
		border-radius: 12rpx;
		margin: 20rpx 0;
	}

	.collapse-container {
		background: #fff;
		border-radius: 12rpx;
		margin-bottom: 20rpx;
		overflow: hidden;

		.collapse-header {
			display: flex;
			align-items: center;
			padding: 30rpx;
			position: relative;

			.collapse-title {
				font-size: 32rpx;
				font-weight: bold;
				color: #333;
			}

			.collapse-value {
				margin-left: auto;
				font-size: 28rpx;
				color: #666;
			}

			.collapse-arrow {
				margin-left: 20rpx;
				font-size: 24rpx;
				color: #999;
				transition: transform 0.3s ease;

				&.arrow-down {
					transform: rotate(180deg);
				}
			}
		}

		.collapse-content {
			padding: 0 30rpx 30rpx;
		}
	}

	// 添加过渡动画
	.slide-fade-enter-active {
		transition: all 0.3s ease-out;
	}

	.slide-fade-leave-active {
		transition: all 0.3s ease-in;
	}

	.slide-fade-enter-from,
	.slide-fade-leave-to {
		transform: translateY(-20rpx);
		opacity: 0;
	}
}
</style>